﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Trock.Learning.SyncFunc
{
    public class Producer
    {
        public BlockingCollection<int> Datas { get; set; }
        bool trigger = false;
        int MaxSize = 10;
        public Producer()
        {
            Datas = new BlockingCollection<int>(100);
            Random rd = new Random(DateTime.Now.Millisecond);
            new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    if (trigger)
                    {
                       if( Datas.TryAdd(rd.Next(10000)))
                        trigger = false;
                       //else
                       //    Console.WriteLine("添加失败");
                    }
                }
            })) { IsBackground = true }.Start();
            new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    if (Datas.Count > MaxSize)
                    {
                        int value = 0;
                        //数据满了就及时清空掉
                        if(! Datas.TryTake(out value, 500))
                            Console.WriteLine("移除失败");
                        //其他操作
                        Console.WriteLine("old data:" + value);
                    }
                }
            })) { IsBackground = true }.Start();
        }

        public bool GetValue(ref int value)
        {
            try
            {
                if (!Datas.TryTake(out value, 1000))
                    throw new Exception("获取超时");
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public int GetValue()
        {
            int data = Datas.Take();
            return data;
        }

        public void Trigger()
        {
            trigger = true;
        }
    }
}
